package lolxxs.chenyanting.interceptor;

import lolxxs.chenyanting.mapper.LogMapper;
import lolxxs.chenyanting.model.Log;
import lolxxs.chenyanting.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private LogMapper logMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
//        System.out.println("经过了拦截器");
//        String header = request.getHeader("Authorization");
//        // 验证请求是否有效
//        Log log = new Log();
//        String url = request.getRequestURL().toString();
//        if (url.length() > 255) {
//            url = url.substring(0, 253);
//        }
//        System.out.println(url);
//        log.setUrl(url);
//        log.setUserId((long)0);
//        log.setState(-1);
//        log.setUserName("未知");
//        String ipAddress = getIpAddress(request);
//        log.setIp(ipAddress);
//        Date date = new Date();
//        log.setCreateTime(date);
//        log.setUpdateTime(date);
//        if (header != null && !"".equals(header)) {
//            if (header.startsWith("CUIT ")) {
//                String token = header.substring(5);
//                // 判断redis库中有无该token
//                if (redisTemplate.opsForValue().get("login_"+token) != null) {
//                    // 插入访问日志
////                    System.out.println(token);
//                    log.setState(1);
//                    Claims claims = jwtUtil.parseJWT(token);
//                    String roles = (String) claims.get("access");
//                    log.setUserId(Long.valueOf(claims.getId()));
//                    log.setUserName(claims.getSubject());
//                    request.setAttribute("claims", claims); // 解析token，获取访问用户id和用户名
//                    if (roles != null && "true".equals(roles)) {
//                        logMapper.insert(log);
//                        return true;
//                    }
//                }
//            }
//        }
//        logMapper.insert(log);
//        // 抛出异常为了给全局异常拦截
//        throw new RuntimeException("请先登录");
        return true;
    }

    private static String getIpAddress(HttpServletRequest request) {
        String Xip = request.getHeader("X_Real_IP");
        String XFor = request.getHeader("Host");
        String host = request.getHeader("X_Forward_For");
        System.out.println(Xip);
        System.out.println(XFor);
        System.out.println(request.getRemoteAddr());
//        return host;
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }
}
